<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>拍照上传测试</title>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
    <style>
        .photo-container {
            max-width: 500px;
            margin: 20px auto;
            padding: 15px;
        }
        .preview-container {
            width: 100%;
            height: 300px;
            border: 2px dashed #ccc;
            margin: 15px 0;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            overflow: hidden;
        }
        #preview {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }
        .camera-btn {
            width: 100%;
            margin: 10px 0;
            padding: 12px;
            font-size: 16px;
        }
        .loading {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.7);
            z-index: 1000;
            color: white;
            text-align: center;
            padding-top: 50%;
        }
        .upload-progress {
            display: none;
            margin: 10px 0;
        }
        #fileInput {
            display: none;
        }
        .btn-group {
            display: flex;
            gap: 10px;
            margin: 15px 0;
        }
        .btn-group .btn {
            flex: 1;
        }
        .location-info {
            margin: 15px 0;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 5px;
            font-size: 14px;
            display: none;  /* 默认隐藏 */
        }
        .location-info p {
            margin: 5px 0;
            color: #666;
        }
        .location-loading {
            color: #666;
            font-style: italic;
        }
    </style>
</head>
<body>
    <div class="photo-container">
        <h3 class="text-center mb-4">拍照上传测试</h3>
        
        <div class="preview-container">
            <img id="preview" src="/static/images/camera-placeholder.png" alt="预览">
        </div>

        <div class="btn-group">
            <button class="btn btn-primary" onclick="openCamera()">
                <i class="bi bi-camera"></i> 拍照
            </button>
            <button class="btn btn-secondary" onclick="openGallery()">
                <i class="bi bi-images"></i> 相册
            </button>
        </div>

        <input type="file" id="fileInput" accept="image/*" capture="environment">
        
        <div class="upload-progress">
            <div class="progress">
                <div class="progress-bar" role="progressbar" style="width: 0%"></div>
            </div>
        </div>

        <button class="btn btn-success camera-btn" onclick="uploadPhoto()" id="uploadBtn" disabled>
            上传图片
        </button>

        <div class="location-info" id="locationInfo">
            <p><strong>位置信息：</strong></p>
            <p>纬度：<span id="latitude">获取中...</span></p>
            <p>经度：<span id="longitude">获取中...</span></p>
            <p>精确度：<span id="accuracy">获取中...</span></p>
            <p>地址：<span id="address">获取中...</span></p>
        </div>
    </div>

    <div class="loading">
        <div class="spinner-border text-light" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
        <p class="mt-2">处理中...</p>
    </div>

    <script src="/static/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentFile = null;
        const fileInput = document.getElementById('fileInput');
        const preview = document.getElementById('preview');
        const uploadBtn = document.getElementById('uploadBtn');
        const loading = document.querySelector('.loading');
        const progressBar = document.querySelector('.progress-bar');
        const progressContainer = document.querySelector('.upload-progress');

        // 添加位置相关变量
        let currentLocation = null;
        const locationInfo = document.getElementById('locationInfo');

        // 打开相机
        function openCamera() {
            getLocation();  // 获取位置信息
            fileInput.setAttribute('capture', 'environment');
            fileInput.click();
        }

        // 打开相册
        function openGallery() {
            getLocation();  // 获取位置信息
            fileInput.removeAttribute('capture');
            fileInput.click();
        }

        // 文件选择处理
        fileInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (!file) return;

            // 验证文件类型
            if (!file.type.startsWith('image/')) {
                alert('请选择图片文件');
                return;
            }

            // 验证文件大小（最大10MB）
            if (file.size > 10 * 1024 * 1024) {
                alert('图片大小不能超过10MB');
                return;
            }

            currentFile = file;
            preview.src = URL.createObjectURL(file);
            uploadBtn.disabled = false;
        });

        // 上传图片
        function uploadPhoto() {
            if (!currentFile) {
                alert('请先选择或拍摄图片');
                return;
            }

            const formData = new FormData();
            formData.append('photo', currentFile);
            
            // 添加位置信息
            if (currentLocation) {
                formData.append('latitude', currentLocation.latitude);
                formData.append('longitude', currentLocation.longitude);
                formData.append('accuracy', currentLocation.accuracy);
            }

            loading.style.display = 'block';
            progressContainer.style.display = 'block';
            uploadBtn.disabled = true;

            // 获取上传token
            fetch('/file/upload_token')
                .then(response => response.json())
                .then(tokenData => {
                    if (tokenData.status !== 200) {
                        throw new Error(tokenData.message || '获取上传凭证失败');
                    }

                    const uploadData = new FormData();
                    uploadData.append('token', tokenData.data.upload_token);
                    uploadData.append('file', currentFile);

                    // 上传到七牛云
                    return fetch(tokenData.data.upload_url, {
                        method: 'POST',
                        body: uploadData
                    });
                })
                .then(response => response.json())
                .then(result => {
                    loading.style.display = 'none';
                    progressContainer.style.display = 'none';
                    alert('上传成功！');
                    
                    // 重置状态
                    currentFile = null;
                    preview.src = '/static/images/camera-placeholder.png';
                    uploadBtn.disabled = true;
                    fileInput.value = '';
                })
                .catch(error => {
                    loading.style.display = 'none';
                    progressContainer.style.display = 'none';
                    uploadBtn.disabled = false;
                    alert('上传失败：' + error.message);
                });
        }

        // 更新进度条
        function updateProgress(percent) {
            progressBar.style.width = percent + '%';
            progressBar.setAttribute('aria-valuenow', percent);
        }

        // 获取位置信息
        function getLocation() {
            if (!navigator.geolocation) {
                console.log('浏览器不支持地理位置');
                return;
            }

            const options = {
                enableHighAccuracy: true,  // 高精度
                timeout: 5000,            // 超时时间
                maximumAge: 0             // 不使用缓存
            };

            navigator.geolocation.getCurrentPosition(
                position => {
                    currentLocation = {
                        latitude: position.coords.latitude,
                        longitude: position.coords.longitude,
                        accuracy: position.coords.accuracy
                    };

                    // 显示位置信息
                    document.getElementById('latitude').textContent = currentLocation.latitude.toFixed(6);
                    document.getElementById('longitude').textContent = currentLocation.longitude.toFixed(6);
                    document.getElementById('accuracy').textContent = `${currentLocation.accuracy.toFixed(1)}米`;

                    // 显示位置信息区域
                    locationInfo.style.display = 'block';

                    // 获取地理位置描述
                    getAddressFromCoords(currentLocation.latitude, currentLocation.longitude);
                },
                error => {
                    console.error('获取位置失败:', error);
                    let errorMessage = '获取位置失败：';
                    switch(error.code) {
                        case error.PERMISSION_DENIED:
                            errorMessage += '用户拒绝了位置请求';
                            break;
                        case error.POSITION_UNAVAILABLE:
                            errorMessage += '位置信息不可用';
                            break;
                        case error.TIMEOUT:
                            errorMessage += '获取位置超时';
                            break;
                        default:
                            errorMessage += '未知错误';
                    }
                    alert(errorMessage);
                },
                options
            );
        }

        // 使用百度地图API获取地址描述
        function getAddressFromCoords(latitude, longitude) {
            const script = document.createElement('script');
            script.src = `https://api.map.baidu.com/geocoder/v2/?ak=您的百度地图AK&callback=handleAddress&location=${latitude},${longitude}&output=json`;
            document.body.appendChild(script);
        }

        // 百度地图回调函数
        window.handleAddress = function(result) {
            if (result.status === 0) {
                document.getElementById('address').textContent = result.result.formatted_address;
            } else {
                document.getElementById('address').textContent = '获取地址失败';
            }
        }
    </script>
</body>
</html> 